import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_extend/share_extend.dart';
import 'package:toolbox/page/home/home_logic.dart';
import 'package:toolbox/widgets/defaultDialog.dart';
import '../../../common/info.dart';
import '../../../common/styles.dart';
import '../../../manager/global.dart';

class HomeDrawer extends StatefulWidget {
  HomeDrawer({super.key});

  @override
  State<HomeDrawer> createState() => _HomeDrawerState();
}

class _HomeDrawerState extends State<HomeDrawer> {
  final logic = Get.find<HomeLogic>();

  double folderSize = 0.0;

  List<String> paths = [];

  @override
  initState() {
    super.initState();
    getFolderSize();
  }

  Future<void> getFolderSize() async {
    String appDocumentsPath = (await getApplicationDocumentsDirectory()).path;
    String tempPath = (await getTemporaryDirectory()).path;
    String appCachePath = (await getApplicationCacheDirectory()).path;
    String appDownloadPath = ((await getDownloadsDirectory())?.path ?? '').replaceAll('downloads', '');
    String appSupportPath = (await getApplicationSupportDirectory()).path ?? '';
    folderSize = 0;
    paths.clear();
    void _getSize(String path) async {
      if (path != '') {
        paths.add(path);
      }
      Directory folder = Directory(path);
      if (await folder.exists()) {
        // 遍历文件夹中的所有文件和子文件夹
        await for (var entity in folder.list(recursive: true)) {
          if (entity is File) {
            folderSize += entity.lengthSync(); // 累加文件大小
            print('name: ${entity.path} folderSize:${entity.lengthSync() / (1000 * 1000)}MB');
            setState(() {});
          }
        }
      } else {
        print('文件夹不存在');
      }
    }

    _getSize('$appDocumentsPath/Trimmer');
    _getSize(tempPath);
    if (tempPath != appCachePath) {
      _getSize(appCachePath);
    }
    _getSize(appDownloadPath);
    _getSize(appSupportPath);
  }

  void onTapClean() async {
    String content = '';
    for(var path in paths){
      content += '- $path\n';
    }
    Get.dialog(
      defaultDialog(
        title: '确认删除？',
        content: content,
        sureFunction: () async {
          for(var path in paths){
            await deleteFolderContent(path);
          }
          await getFolderSize();
          setState(() {});
        }
      ),
    );
  }

  Future<void> deleteFolderContent(String path) async {
    Directory folder = Directory(path);
    if (await folder.exists()) {
      // 列出文件夹中的所有文件和子文件夹
      await for (var entity in folder.list()) {
        try {
          if (entity is File) {
            await entity.delete(); // 删除文件
            print('删除文件: ${entity.path}');
          } else if (entity is Directory) {
            await entity.delete(recursive: true); // 删除子文件夹及其内容
            print('删除文件夹: ${entity.path}');
          }
        } catch (e) {
          print('Error deleting ${entity.path}: $e');
        }
      }
      print('清除完毕$path');
    } else {
      print('${folder.path}路径不存在');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: SafeArea(
        child: Column(
          children: [
            listTile(
              text: '翻译',
              icon: const Icon(Icons.g_translate),
              onTap: logic.onTapTranslate,
            ),
            defaultDivider(),
            listTile(
              text: '二维码生成与扫描',
              icon: const Icon(Icons.qr_code),
              onTap: logic.onTapQr,
            ),
            defaultDivider(),
            listTile(
              text: '视频编辑',
              icon: const Icon(Icons.video_settings_outlined),
              onTap: logic.onTapVideoEdit,
            ),
            defaultDivider(),
            listTile(
              text: 'Web',
              icon: const Icon(Icons.web),
              onTap: logic.onTapBrowserPage,
            ),
            defaultDivider(),
            listTile(
              text: '清理缓存',
              subtitle: '${folderSize / (1000 * 1000)}/MB',
              icon: const Icon(Icons.cleaning_services),
              onTap: onTapClean,
            ),
            defaultDivider(),
            const Spacer(),
            Align(
              alignment: Alignment.centerRight,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                      onPressed: () {
                        ShareExtend.share(
                          Info.gitHomeUrl,
                          'text',
                          sharePanelTitle: '选择应用打开或分享',
                          subject: Info.appName,
                          extraText: '选择应用打开或分享',
                        );
                      },
                      icon: const Icon(Icons.share)),
                  IconButton(
                    onPressed: () => GlobalUtil.getInstance().checkVersion(
                      showTrue: true,
                      alwaysShowDialog: true,
                    ),
                    icon: const Icon(Icons.tips_and_updates_outlined),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 10),
          ],
        ),
      ),
    );
  }

  Widget listTile({
    Widget? icon,
    required String text,
    String? subtitle,
    String? rightTitle,
    Function()? onTap,
  }) {
    return ListTile(
      leading: icon,
      title: Text(
        text,
        style: Styles.textStyle(size: 18),
      ),
      subtitle: subtitle != null ? Text(subtitle) : null,
      onTap: onTap,
    );
  }

  Widget defaultDivider({double padding = 0}) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: padding),
      child: const Divider(
        color: Colors.grey,
        height: 1,
      ),
    );
  }
}
